package sk.ogame.realm.mapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import sk.ogame.realm.entity.Star;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 支绍昆
 * 2023/2/1
 * 星球
 **/
@Service
public class StarMapper {

    private static final Logger log = LoggerFactory.getLogger(StarMapper.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insert(List<Star> starList) {
        try {
            jdbcTemplate.batchUpdate("INSERT INTO star(id,galaxy,system,slot,lately,attack,rank,build,resource) " +
                            "VALUES (?,?,?,?,?,?,?,?,?)",
                    starList,
                    starList.size(), (ps, star) -> {
                        ps.setInt(1, star.getId());
                        ps.setInt(2, star.getGalaxy());
                        ps.setInt(3, star.getSystem());
                        ps.setInt(4, star.getSlot());
                        ps.setInt(5, star.getLately());
                        ps.setInt(6, star.getAttack());
                        ps.setInt(7, star.getRank());
                        ps.setInt(8, star.getBuild());
                        ps.setInt(9, star.getResource());
                    });
        } catch (DuplicateKeyException duplicateKeyException) {
            log.error("save star duplicate key : [{}]", duplicateKeyException.getMessage());
            throw duplicateKeyException;
        }
    }

    public List<Star> selectAll() {
        return jdbcTemplate.query("SELECT * FROM star ORDER BY id", new RowMapper<Star>() {
            @Override
            public Star mapRow(ResultSet rs, int rowNum) throws SQLException {
                Star star = new Star();
                star.setId(rs.getInt("id"));
                star.setGalaxy(rs.getInt("galaxy"));
                star.setSystem(rs.getInt("system"));
                star.setSlot(rs.getInt("slot"));
                star.setLately(rs.getInt("lately"));
                star.setAttack(rs.getInt("attack"));
                star.setRank(rs.getInt("rank"));
                star.setBuild(rs.getInt("build"));
                star.setResource(rs.getInt("resource"));
                return star;
            }
        });
    }

    public int delById(int id) {
        if (id < 0) {
            return 0;
        }
        return jdbcTemplate.update("DELETE FROM star WHERE id =" + id);
    }

}
